package com.itheima.admin.task;

import com.itheima.admin.service.WemediaNewsAutoScanService;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmNewsPageReqDto;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.vo.WmNewsVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.groovy.runtime.dgmimpl.arrays.ShortArrayPutAtMetaMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class SyncArticleTask {
    @Autowired
    private WmNewsFeign wmNewsFeign;

    @Autowired
    private WemediaNewsAutoScanService wemediaNewsAutoScanService;

    @XxlJob("syncArticleTask")
    public ReturnT<String> syncArticleJob(String param) {
        log.info("开始执行同步文章任务:param={}", param);

        //远程调用自媒体查询文章
        WmNewsPageReqDto wmNewsPageReqDto = new WmNewsPageReqDto();
        wmNewsPageReqDto.setStatus((short) BusinessConstants.WmNewsConstants.STATUS_PASS);
        wmNewsPageReqDto.setEndPubDate(new Date());
        ResultVo<List<WmNewsVo>> listResultVo = wmNewsFeign.list4ArticleSync(wmNewsPageReqDto);

        //对结果判断
        if (listResultVo.isSuccess()) {
            List<WmNewsVo> list = listResultVo.getData();
            log.info("同步文章任务完成: param={},size={}", param, list.size());
            XxlJobLogger.log("同步文章任务: size={}", list.size());
            if (!CollectionUtils.isEmpty(list)) {
                //有需要同步的数据
                for (WmNewsVo wmNewsVo : list) {
                    //同步文章数据
                    boolean flag = wemediaNewsAutoScanService.syncArticleInfo(wmNewsVo);
                    if (flag) {
                        log.info("同步文章数据成功: wmNewsId={}", wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据成功: wmNewsId={}", wmNewsVo.getId());
                    } else {
                        log.info("同步文章数据失败: wmNewsId={}", wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据失败: wmNewsId={}", wmNewsVo.getId());
                    }
                }
            }
            log.info("结束执行同步文章任务:param={}",param);
            return ReturnT.SUCCESS;
        }else {
            log.info("同步文章任务失败: param={}， 调用自媒体微服查询失败", param);
            return ReturnT.FAIL;
        }
    }

    @XxlJob("mytestTask")
    public ReturnT<String> handlerTask(String param){
        System.out.println("执行成功"+param);
        return ReturnT.SUCCESS;
    }
}

